<template>
    <div class="worker-init" style="display: none"></div>
</template>
<script>
import Worker from './inter.worker.js'
import {
    getCookie,
    getLangByUrl,
    setCookie,
    formatRateDate,
    formatRateDateNew,
    setItem,
    switchName,
    loginOutAndClearInfo,
    delCookie,
    toThousands,
    countNum,
} from '@/util'
import { appKey } from '@/api/enmu'
import { mapState, mapActions, mapMutations, mapGetters } from 'vuex'
import { listSymbolByLabel } from '@/api/index'
let SpotTimes = 0 // 现货所有币种价格推送次数
let SwapUTimes = 0 // SwapU所有币种价格推送次数
let SwapCTimes = 0 // SwapC所有币种价格推送次数
let SwapBTimes = 0 // SwapB所有币种价格推送次数
let SwapTimes = 0 // Swap所有币种价格推送次数
let Type = '',
    InstrumentID = '',
    InstrumentName = '' // 当前订阅币种的价格以及币种名称
let oldPrice = 0

export default {
    name: 'wsMsg',
    data() {
        return {
            SwapLastPrice:'',       // 合约K线返回的最新价格
            SpotLastPrice:'',       // 现货K线返回的最新价格
        }
    },
    computed: {
        ...mapGetters(['SpotRepaired']),
        ...mapState([
            'locale',
            'token',
            'uid',
            'SpotList',
            'currencyRate',
            'localCurrency',
            'SwapUList',
            'SwapCList',
            'SwapBList',
            'SwapList',
            'SpotwsStatus',
            'SwapwsStatus',
            'SpotLiveList',
            'SwapLiveList',
            // 'spotListPrice',
            // 'swapUListPrice',
            // 'swapCListPrice',
            // 'swapBListPrice',
            // 'swapListPrice',
        ]),
        ...mapState('swapQuot1', [
            'connectSystemStatus',
            'marketListItem'
        ]),
        ...mapState('swapCommon1', [
            'connectErrInfo'
        ]),
        ...mapGetters('swapQuot1', [
            'priceNum',
        ]),
        ...mapState('spotQuot', [
            'marketDataThis',
        ]),
    },
    watch: {
        '$route':{
            handler(n,o){
                if (window.DCworker) {
                    window.DCworker.postMessage({
                        type: 'SwapSpot',
                        action: 'pageRouter',
                        value: n.path,
                    })
                }
            },
            immediate:true
        },
        SpotRepaired(n, o) {
            let send = () => {
                if (window.DCworker) {
                    window.DCworker.postMessage({
                        type: 'Spot',
                        action: 'isSpotInRepaired',
                        value: n,
                    })
                } else {
                    setTimeout(() => {
                        send()
                    }, 300)
                }
            }
            send()
        },
        currencyRate: {
            handler(n, o) {
                if (n && Object.keys(n).length) this.sendCurrencyRate()
            },
            immediate: true,
        },
        localCurrency: {
            handler(n, o) {
                if (n != o) this.sendCurrencyRate()
            },
            immediate: true,
        },
        SpotList: {
            handler(n, o) {
                if (n && n.length) {
                    // 将现货币种列表发送到web worker
                    let send = () => {
                        if (window.DCworker) {
                            window.DCworker.postMessage({
                                type: 'Spot',
                                action: 'SpotList',
                                value: n,
                            })
                        } else {
                            setTimeout(() => {
                                send()
                            }, 300)
                        }
                    }
                    send()
                }
            },
            immediate: true,
        },
        SwapUList: {
            handler(n, o) {
                if (n && n.length) {
                    let send = () => {
                        // 发送币种列表到web worker
                        if (window.DCworker) {
                            window.DCworker.postMessage({
                                type: 'SwapMarketData',
                                action: 'SwapUList',
                                value: n,
                            })
                        } else {
                            setTimeout(() => {
                                send()
                            }, 300)
                        }
                    }
                    send()
                }
            },
            immediate: true,
        },
        SwapCList: {
            handler(n, o) {
                if (n && n.length) {
                    let send = () => {
                        // 发送币种列表到web worker
                        if (window.DCworker) {
                            window.DCworker.postMessage({
                                type: 'SwapMarketData',
                                action: 'SwapCList',
                                value: n,
                            })
                        } else {
                            setTimeout(() => {
                                send()
                            }, 300)
                        }
                    }
                    send()
                }
            },
            immediate: true,
        },
        SwapBList: {
            handler(n, o) {
                if (n && n.length) {
                    let send = () => {
                        // 发送币种列表到web worker
                        if (window.DCworker) {
                            window.DCworker.postMessage({
                                type: 'SwapMarketData',
                                action: 'SwapBList',
                                value: n,
                            })
                        } else {
                            setTimeout(() => {
                                send()
                            }, 300)
                        }
                    }
                    send()
                }
            },
            immediate: true,
        },
        SwapList: {
            handler(n, o) {
                if (n && n.length) {
                    let send = () => {
                        if (window.DCworker) {
                            window.DCworker.postMessage({
                                type: 'SwapMarketData',
                                action: 'SwapList',
                                value: n,
                            })
                        } else {
                            setTimeout(() => {
                                send()
                            }, 300)
                        }
                    }
                    send()
                }
            },
            immediate: true,
        },
        SpotLiveList(n, o) {
            let send = () => {
                if (window.DCworker) {
                    window.DCworker.postMessage({
                        type: 'Spot',
                        action: 'SpotLiveList',
                        value: n,
                    })
                } else {
                    setTimeout(() => {
                        send()
                    }, 300)
                }
            }
            send()
        },
        SwapLiveList(n, o) {
            let send = () => {
                if (window.DCworker) {
                    window.DCworker.postMessage({
                        type: 'Swap',
                        action: 'SwapLiveList',
                        value: n,
                    })
                } else {
                    setTimeout(() => {
                        send()
                    }, 300)
                }
            }
            send()
        },
    },
    methods: {
        ...mapMutations(['setSymbolByLabel', 'setSpotwsStatus', 'setSwapwsStatus', 'setDocumentVisibility']),
        ...mapMutations('spotCommon', ['setConnectErrInfo']),
        ...mapMutations('spotQuot', [
            'setTradeList',
            'setSpotBidList',
            'setSpotAskList',
            'setKlineLines',
            'setRefreshTradingView',
            'setMarketDataThis',
            'setRefreshBalance',
            'setConnectSystemStatus',
        ]),
        ...mapMutations('swapCommon1', ['setSwapConnectErrInfo']),
        ...mapMutations('swapQuot1', [
            'setSwapTradeList',
            'setRateTime',
            'setPosTimeStr',
            'setStateEndTime',
            'setMarketListItem',
            'setSwapAskList',
            'setSwapBidList',
            'setSwapKlineLines',
            'setReloadKline',
            'setPushOrderDate',
            'setSwapConnectSystemStatus',
        ]),
        ...mapMutations([
            // 'setSpotListPrice',
            // 'setSwapUListPrice',
            // 'setSwapCListPrice',
            // 'setSwapBListPrice',
            // 'setSwapListPrice',
            'setNetWorkErrTip',
            'setSpotPriceList',
            'setSwapPriceList',
        ]),
        sendCurrencyRate() {
            // 发送汇率、本地货币到web worker
            let send = () => {
                if (window.DCworker) {
                    if (this.currencyRate && Object.keys(this.currencyRate).length && this.localCurrency) {
                        window.DCworker.postMessage({
                            type: 'Spot',
                            action: 'currencyRate',
                            value: {
                                currencyRate: this.currencyRate,
                                localCurrency: this.localCurrency,
                            },
                        })
                    }
                } else {
                    setTimeout(() => {
                        send()
                    }, 300)
                }
            }
            send()
        },
        currentTabHidden() {
            //监听页面进入到后台后退订
            document.addEventListener(
                'visibilitychange',
                (e) => {
                    // 现货
                    clearTimeout(window.SwapSpotTimer)
                    if (document.hidden) {
                        window.SwapSpotTimer = setTimeout(() => {
                            this.setSwapwsStatus('stop')
                            this.setSpotwsStatus('stop')
                            this.setDocumentVisibility(false)
                            window.DCworker.postMessage({
                                type: 'SwapSpot',
                                action: 'pageStatus',
                                value:'hidden'
                            })
                        }, 0.5 * 60 * 1000)
                    } else {
                        this.setDocumentVisibility(true)
                        if (window.DCworker && this.SwapwsStatus === 'stop') {
                            this.setSwapwsStatus('')
                            this.setSpotwsStatus('')
                            window.DCworker.postMessage({
                                type: 'SwapSpot',
                                action: 'pageStatus',
                                value:'show'
                            })
                        }
                    }
                },
                false
            )
        },
        setTitle(Price, InstrumentName) {
            window.arrowUpDown =
                Number(Price) > Number(window.oldPrice)
                    ? '▲'
                    : Number(Price) < Number(window.oldPrice)
                    ? '▼'
                    : window.arrowUpDown
            document.title =
                (window.arrowUpDown ? window.arrowUpDown : '') +
                ' ' +
                toThousands(Price) +
                ' | ' +
                InstrumentName +
                ' - Deepcoin'
            window.oldPrice = Price
        },
        renderSpot(res) {
            // 只接收现货数据
            if(res.action === 'refreshPrice') {
                // 只更新title
                this.setTitle(res.value.Price, res.value.InstrumentName);
            }
            // if(res.action === 'tradeList'){
            //     //实时成交列表
            //     this.setTradeList(res.value)
            // }
            if (res.action === 'panList') {
                //盘口数据
                this.setSpotBidList(res.value.bidList)
                this.setSpotAskList(res.value.askList)
                //推送盘口的时候默认链接正常
                this.setConnectSystemStatus(1)
                this.setConnectErrInfo(false)
            }
            if(res.action === 'Kline'){
                //实时K线
                // this.SpotLastPrice = res.value.LastPrice;
                // this.marketDataThis.LastPrice = this.SpotLastPrice;
                // this.marketDataThis.Price = this.SpotLastPrice;
                // this.setMarketDataThis(this.marketDataThis);
                
                // this.setKlineLines(res.value)
            }
            if (res.action === 'reloadKline') {
                //通知K线重新加载
                this.setRefreshTradingView(+new Date())
            }
            if (res.action === 'marketDataThis') {
                //当前币种快照
                // res.value.LastPrice = this.SpotLastPrice;
                // res.value.Price = this.SpotLastPrice;
                this.setMarketDataThis(res.value)
                this.$nextTick(() => {
                    if (this.$route.path === '/Spot') {
                        Type = 'Spot'
                        InstrumentName = res.value.InstrumentName
                        InstrumentID = res.value.InstrumentID
                        this.setTitle(res.value.Price, res.value.InstrumentName)
                    }
                })
            }
            if (res.action === 'systemStatus') {
                //系统连接状态
                this.setConnectSystemStatus(res.value)
            }
            if (res.action === 'marketData') {
                //现货所有币种价格
                // console.log(res.value)
                this.setSpotPriceList(res.value)
                // if(Array.isArray(res.value) && res.value.length){
                //     for(let item of res.value){
                //         let find = this.spotListPrice.find(ele => ele.Type === item.Type && ele.InstrumentID === item.InstrumentID);
                //         if(find){
                //             find.HighestPrice = item.HighestPrice;
                //             find.LastPrice = item.LastPrice;
                //             find.LowestPrice = item.LowestPrice;
                //             find.OpenInterest = item.OpenInterest;
                //             find.OpenPrice = item.OpenPrice;
                //             find.ProductGroup = item.ProductGroup;
                //             find.Turnover = item.Turnover;
                //             find.UpdateTime = item.UpdateTime;
                //             find.Volume = item.Volume;
                //         }else{
                //             this.spotListPrice.push(item)
                //         }
                //     }
                //     this.setSpotListPrice(this.spotListPrice);
                // }
                // SpotTimes++;
                // let _parseInt = SpotTimes/8;
                // if(Math.floor(_parseInt) === _parseInt) setCookie('SpotPriceList',res.value);
                // if(SpotTimes > 100000) SpotTimes = 0;
            }
            if (res.action === 'connectErrInfo') {
                //连接异常提示
                this.setConnectErrInfo(res.value)
                if (res.value) this.setNetWorkErrTip(false)
            }
            if (res.action === 'refreshBalance') {
                // 更新余额(持仓)
                console.log('更新余额(持仓)')
                this.setRefreshBalance(res.value)
            }
            if (res.type === 'SpotLogin') {
                if (res.action === 'UserNoPermission') {
                    // token无效
                    delCookie('token')
                    delCookie('Otoken')
                    delCookie('uid')
                    delCookie('userInfo')
                    window.location.reload()
                }
            }
        },
        renderSwap(res) {
            if(res.action === 'refreshPrice') {
                // 只更新title
                this.setTitle(res.value.Price, res.value.InstrumentName);
            }
            if (this.connectErrInfo) this.setSwapConnectErrInfo(false)
            if (this.connectSystemStatus != 1) this.setSwapConnectSystemStatus(1)
            if (res.action === 'marketItem') {
                //当前订阅币种最新价格
                res.value.Price = this.SwapLastPrice;
                res.value.LastPrice = this.SwapLastPrice;
                this.setMarketListItem(res.value);

                // 当前8小时资金费率结算时间
                let UpdateTime = res.value.UpdateTime;
                // 新版资金费率结算
                let PositionFeeTime = res.value.PositionFeeTime;
                if (UpdateTime && !PositionFeeTime) {
                    //更新UpdateTime字段
                    // this.setRateTime(formatRateDate(UpdateTime))
                    // this.setPosTimeStr(formatRateDate(UpdateTime + 8 * 3600))
                    this.setStateEndTime(formatRateDate(UpdateTime, true))
                }
                
                if(PositionFeeTime){
                    this.setStateEndTime(formatRateDateNew(PositionFeeTime))
                }
                // 更新title
                this.$nextTick(() => {
                    if (this.$route.path.includes('/Swap')) {
                        Type = res.value.Type
                        InstrumentID = res.value.InstrumentID
                        InstrumentName = res.value.InstrumentName
                        this.setTitle(res.value.Price, InstrumentName)
                    }
                })
            }
            // if(res.action === 'tradeList'){
            //     //实时成交列表
            //     this.setSwapTradeList(res.value)
            // }
            if (res.action === 'panList') {
                //盘口数据
                this.setSwapAskList(res.value.askList)
                this.setSwapBidList(res.value.bidList)
                //推送盘口的时候，默认连接正常
                this.setSwapConnectSystemStatus(1)
                this.setSwapConnectErrInfo(false)
            }
            if(res.action === 'Kline'){
                //实时K线
                this.SwapLastPrice = countNum(res.value.ClosePrice,this.priceNum);
                this.marketListItem.Price = this.SwapLastPrice;
                this.marketListItem.LastPrice = this.SwapLastPrice;
                this.setMarketListItem(this.marketListItem);
            }
            if (res.action === 'reloadKline') {
                //通知K线重新加载
                this.setReloadKline(+new Date())
            }
            if (res.action === 'systemStatus') {
                //系统连接状态
                this.setSwapConnectSystemStatus(res.value)
            }
            if (res.action === 'marketData') {
                //合约所有币种价格
                this.setSwapPriceList(res.value)
            }
            if(res.action === 'pushTriggerOrder') {    //监听订单变动
                console.log(res.action,'PushTriggerOrder')
            }
            if(res.action === 'pushOrder') {    //监听订单变动
                console.log(res.action,'PushOrder')
            }
            if (res.action === 'connectErrInfo') {
                //连接异常提示
                this.setSwapConnectErrInfo(res.value)
                if (res.value) this.setNetWorkErrTip(false)
            }
        },
        initWebWorker() {
            //初始化web worker
            window.DCworker = new Worker()
            window.DCworker.postMessage({
                type: 'baseInfo',
                action: 'baseInfo',
                value: {
                    device: getCookie('device'),
                    lang: this.locale,
                    token:this.token,
                    uid:this.uid,
                    appid:appKey.appid,
                },
            })

            window.DCworker.addEventListener('message', (ev) => {
                let res = ev.data
                // if(res.type === 'baseInfo' && res.action === 'getSymbolByLabel'){
                //     // 所有币种(现货、合约)分类列表
                //     this.setSymbolByLabel(res.value);
                //     setItem('getSymbolByLabel-'+this.locale,JSON.stringify(res.value));
                // }
                if (res.type === 'Spot' || res.type === 'SpotLogin' || res.type === 'SwapSpot') {
                    // let date = new Date();
                    // console.log(date.getMinutes()+':'+date.getSeconds()+'======'+JSON.stringify(res))
                    this.renderSpot(res)
                }
                if (res.type === 'Swap' || res.type === 'SwapU' || res.type === 'SwapC' || res.type === 'SwapB') {
                    this.renderSwap(res)
                }
                if (
                    res.type === 'SwapLogin' ||
                    res.type === 'SwapULogin' ||
                    res.type === 'SwapCLogin' ||
                    res.type === 'SwapBLogin'
                ) {
                    if (res.action === 'pushOrderDate') {
                        //订单变化-更新持仓、资金
                        this.setPushOrderDate(+new Date())
                    }
                    // if(res.action === 'pushTriggerOrder') {    //监听订单变动
                    //     console.log(res.action,'PushTriggerOrder')
                    // }
                    // if(res.action === 'pushOrder') {    //监听订单变动
                    //     console.log(res.action,'PushOrder')
                    // }
                    if (res.action === 'UserNoPermission') {
                        // token无效
                        delCookie('token')
                        delCookie('Otoken')
                        delCookie('uid')
                        delCookie('userInfo')
                        window.location.reload()
                    }
                }
            })
        },
    },
    created() {
        this.initWebWorker()
        // 币种分类
        listSymbolByLabel().then((res) => {
            if (res && res.retCode === 0) {
                this.setSymbolByLabel(res.retData)
                setItem('getSymbolByLabel-' + this.locale, JSON.stringify(res.retData))
            }
        });
    },
    mounted() {
        this.currentTabHidden()
    },
}
</script>
